<template>
	<view id="body">
		<view class="navimg">
			<!-- 轮播图 -->
			<view class="u-demo-block">
				<u-swiper
					:list="goodsinfo.imglist"
					previousMargin="30"
					nextMargin="30"
					circular
					:autoplay="true"
					interval=4000
					radius="5"
					bgColor="#ffffff"
				></u-swiper>
			</view>
		</view>
		<view class="order-price-sc">
			<view class="left-price">
				<text>￥</text>
				<text style="line-height: 56rpx;">{{goodsinfo.price}}</text>
			</view>
			<view class="right-sc" @click="toggleFavorite">
				<image v-if="goodsinfo.isFavorite" src="../static/img/collection.png" style="width: 40rpx;height: 40rpx;"></image>
				<image v-else src="../static/img/noCollection.png" style="width: 40rpx;height: 40rpx;"></image>
			</view>

		</view>
		<view class="order-conent">
			<view class="title">
				<text>商品名称:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.title}}</text>
			</view>
			<view class="content">
				<text>商品描述:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.content}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="id">
				<text>商品编号:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.id}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="type">
				<text>商品分类:</text>
				<text style="margin-left: 24rpx;">{{type[goodsinfo.type].name}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="oldnew">
				<text>新旧程度:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.lodandnew}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="specifications">
				<text>规格:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.norms}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="sscolor">
				<text>颜色:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.color}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="sscolor">
				<text>型号:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.model}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			<view class="issusername">
				<text>卖家名称:</text>
				<text style="margin-left: 24rpx;">{{goodsinfo.issueUserName}}</text>
			</view>
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
		</view>
		<!-- 底部购物车 -->
		<view class="cart">
			<view class="xt">
				<u-line color="#acacac"></u-line>
			</view>
			

			<view class="issueUser" @click="contact" style="margin-right: 400rpx;" v-if="goodsinfo.state == 1">
				<text class="t-icon t-icon-xiaoxi" style="width: 68rpx; height: 68rpx;"></text>
			</view>

			<!-- 立即购买 -->
			<view class="ljfk" :class="{ disabled: goodsinfo.state === -1 || goodsinfo.state === 3 }">
			    <text v-if="goodsinfo.state === -1">已下架</text>
			    <text v-if="goodsinfo.state === 0" @click="ljfk">立即购买</text>
			    <text v-if="goodsinfo.state === 1" @click="contact">进行联系</text>
			    <text v-if="goodsinfo.state === 3">已完成</text>
			</view>



		</view>
	</view>
</template>

<script>
	import {http} from "../static/service/requestAddress/rtas.js"
	export default {
		data() {
			return {
				isPaying: false, // 是否正在支付
				//商品分类
				type:[
					{
						name:"电子产品",
					},
					{
						name:"生活用品",
					},
					{
						name:"学习用品",
					},
					{
						name:"交通工具",
					},
					{
						name:"其他",
					},
				],
				goodsinfo:{
					id:"",//商品id
					imglist:[],//商品图片信息
					type:0,//商品类型
					price:"",//商品价格
					title:"",//商品标题
					content:"",//订单内容
					lodandnew:"",//新旧程度
					norms:"",//规格
					color:"",//颜色
					model:"",//型号
					issueUserName:"",//发布用户
					number:1,//商品个数
					issueUserImg:"",//用户头像
					state:0,//订单状态
					isFavorite: false,
					module : "tzmarket",
				},
			}
		},
		onShow() {
			this.isPaying = false; // 无论成功还是失败，都重新启用按钮
		},
		methods:{
			// 添加收藏或取消收藏
			async toggleFavorite(index) {
				if(! uni.getStorageSync("user")){
					uni.$u.toast("登录后才能收藏喔")
					return
				}
			    try {
			        var userStr = uni.getStorageSync('user');
			        var user = JSON.parse(userStr);
			        const userId = user.id;
					// 使用商品ID作为唯一键
					const favoriteKey = `isFavorite_${userId}_${this.goodsinfo.id}`;
			        // 查询当前商品是否已经被用户收藏
			        const isFavoriteResponse = await uni.request({
			            url: http + "favorites/check",
			            method: "GET",
			            data: {
			                userId: userId,
			                productId: this.goodsinfo.id,
			            },
			        });

			        // 检查是否成功获取检查结果
			        if (isFavoriteResponse && isFavoriteResponse[1].data) {
			            if (this.goodsinfo.isFavorite) {
			                // 商品已经被用户收藏，执行取消收藏操作
			                const unfavoriteResponse = await uni.request({
			                    url: http + `favorites/remove/${userId}/${this.goodsinfo.id}`,
			                    method: "DELETE",
			                    data: {
			                        userId: userId,
			                        productId: this.goodsinfo.id,
			                    },
			                });

			                // 判断取消收藏的结果
			                if (unfavoriteResponse && unfavoriteResponse[1].data.code === 20050) {
			                    // 取消收藏成功
			                    console.log('取消收藏成功', unfavoriteResponse[1]);
			                    this.goodsinfo.isFavorite = false;
			                    uni.removeStorageSync(favoriteKey);
			                } else {
			                    console.log('取消收藏失败', unfavoriteResponse[1]);
			                    // 其他处理...
			                }
			            } else {
			                // 商品未被用户收藏，执行收藏操作
			                const favoriteResponse = await uni.request({
			                    url: http + "favorites/add",
			                    method: "POST",
			                    data: {
			                        userId: userId,
			                        productId: this.goodsinfo.id,
			                        favoriteTime: new Date().toISOString().slice(0, 19).replace("T", " "),
									module:this.goodsinfo.module,
			                        productTitle: this.goodsinfo.title,
			                        productImage: this.goodsinfo.imglist[0],
			                        productPrice: this.goodsinfo.price,
			                    },
			                });

			                // 判断收藏的结果
			                if (favoriteResponse && favoriteResponse[1].data.code === 20060) {
			                    // 收藏成功
			                    console.log('收藏成功', favoriteResponse[1]);
			                    this.goodsinfo.isFavorite = true;
			                    uni.setStorageSync(favoriteKey, this.goodsinfo.isFavorite);
			                } else {
			                    console.log('收藏失败', favoriteResponse[1]);
			                    // 其他处理...
			                }
			            }
						// 手动更新isFavorite值，触发视图更新
						            this.$forceUpdate();
			        } else {
			            console.error('获取收藏状态失败，无效的响应格式', isFavoriteResponse);
			        }
			    } catch (error) {
			        console.error('操作收藏失败', error);
			        // 处理请求失败的情况
			    }
			},


			onLoad(options){ //页面接收信息
				// const storedIsFavorite = uni.getStorageSync('isFavorite');
				// this.isFavorite = storedIsFavorite !== null ? storedIsFavorite : false;
				var userStr = uni.getStorageSync('user');
				var user = JSON.parse(userStr);
				const userId = user.id;
				console.log("接收的页面信息是:"+options.data)
				var data =  JSON.parse(options.data)
				this.goodsinfo = data
				this.goodsinfo.price = ""+data.price
				this.goodsinfo.imglist = data.orderImg.split(",")
				this.goodsinfo.type = data.type - 1
				this.goodsinfo.isFavorite=false;
				this.goodsinfo.module="tzmarket"
				this.goodsinfo.isFavorite=false;
				// 使用商品ID作为唯一键加载isFavorite状态
				const favoriteKey = `isFavorite_${userId}_${this.goodsinfo.id}`;
				const storedIsFavorite = uni.getStorageSync(favoriteKey);
				this.goodsinfo.isFavorite = storedIsFavorite !== null ? storedIsFavorite : false;
			},
			onShow() {
				  var userStr = uni.getStorageSync('user');
				  var user = JSON.parse(userStr);
				  const userId = user.id;
			      // 当页面显示或重新加载时，从本地存储加载isFavorite状态
			      const favoriteKey = `isFavorite_${userId}_${this.goodsinfo.id}`;
			      const storedIsFavorite = uni.getStorageSync(favoriteKey);
			      this.goodsinfo.isFavorite = storedIsFavorite !== null ? storedIsFavorite : false;
				  },
			//联系商家
			contact(){
										//添加用户到消息列表
										uni.navigateTo({
											url:"/see/chatpage"+"?id="+this.goodsinfo.issueUser+"&name="+this.goodsinfo.issueUserName+"&img="+this.goodsinfo.issueUserImg
										})
									},

			//添加购物车
			addcart(){
				if(! uni.getStorageSync("user")){
					uni.$u.toast("登录后才能添加购物车喔")
					return
				}
				uni.showLoading({
					title:"正在添加中",
					mask: true
				})
				//获取缓存数组
				var list = uni.getStorageSync("cartlist")
				//缓存为空
				if(list == ""){
					var falg = []
					falg.push(this.goodsinfo)
					uni.setStorageSync("cartlist",JSON.stringify(falg))
					uni.$u.toast("添加购物车成功!")
				}else{//有数据的情况
					var falg = JSON.parse(list)
					//查询是否是重复商品
					for(var i = 0;i<falg.length;i++){
						if(falg[i].id == this.goodsinfo.id){
							//商品已经存在
							uni.$u.toast("商品已在购物车!")
							return
						}
					}
					//不存在的情况
					falg.push(this.goodsinfo)
					uni.setStorageSync("cartlist",JSON.stringify(falg))
					uni.$u.toast("添加购物车成功!")
				}
			},
			ljfk() {
			    if (!uni.getStorageSync("user")) {
			        uni.$u.toast("登录后才能购买喔");
			        return;
			    }
			    if (this.isPaying) {
			        // 如果正在支付，则不执行任何操作
			        return;
			    }
			
			    this.isPaying = true; // 标记为正在支付
			    uni.showLoading({
			        title: '正在拉起支付中'
			    });
			
			    // 模拟短暂延迟
			    setTimeout(() => {
			        uni.hideLoading(); // 隐藏加载提示
			        uni.$u.toast("请选择支付结果");
			
			        // 模拟用户选择“支付成功”或“支付失败”的弹窗
			        uni.showModal({
			            title: "支付结果模拟",
			            content: "请选择支付结果：",
			            showCancel: true,
			            cancelText: "支付失败",
			            confirmText: "支付成功",
			            success: (res) => {
			                if (res.confirm) {
			                    // 用户点击“支付成功”
			                    this.handlePaymentSuccess();
			                } else if (res.cancel) {
			                    // 用户点击“支付失败”
			                    uni.$u.toast("支付失败，请重试！");
			                    this.isPaying = false; // 支付失败重新启用按钮
			                }
			            }
			        });
			    }, 1000); // 模拟延迟1秒
			},
			
			handlePaymentSuccess() {
			    // 假设这里已经获取到了必要的信息，如订单ID、用户ID等
			    const orderid = this.goodsinfo.id;
			    const user = JSON.parse(uni.getStorageSync('user'));
			    const url = `${http}tzmarket/${orderid}/${user.id}`;
			
			    console.log("请求的链接是:", url);
			
			    uni.request({
			        url: url,
			        method: "PUT",
			        complete: (res) => {
			            if (res.data.code === 20041) {
			                uni.$u.toast("支付成功！");
			                setTimeout(() => {
			                    // 支付成功后跳转到已支付订单里
			                    uni.redirectTo({
			                        url: "/myorder/order",
			                    });
			                }, 1000);
			            } else {
			                uni.$u.toast("支付状态更新失败，请稍后重试！");
			            }
			            this.isPaying = false; // 支付完成后启用按钮
			        }
			    });
			}


		}
	}
</script>

<style scoped>
	@import url("../static/css/componentsCss/tzmarketindex/tzmarketInfo.css");
</style>
